<template>
  <div class="PictureUpload">
    <p v-show="file.name">名称：{{ file.name }}，格式：{{ file.type }}</p>
    <label for="upload" class="upload">浏览</label>
    <input
      name="upload"
      id="upload"
      type="file"
      accept="image/*"
      @change="getFlie"
    />
  </div>
</template>
<script>
export default {
  name: "PictureUpload",

  data() {
    return {
      file: {
        // 图片数据
        img: "",
        // 全称
        fullName: "",
        // 名称
        name: "",
        // 格式
        type: "",
      },
    };
  },
  methods: {
    // 获取本地文件
    getFlie(e) {
      let fil = e.target.files;
      this.file.fullName = fil[0].name;
      let reader = new FileReader();
      reader.readAsDataURL(fil[0]);
      //onload是FileReader对象里的方法，表示图片上传完成且没有错误就会触发onload事件
      reader.onload = () => {
        this.file.img = reader.result;
      };
    },
  },
  watch: {
    file: {
      handler(newVal, oldVal) {
        if (newVal?.fullName) {
          this.$set(this.file, "name", newVal.fullName.split(".")[0]);
          this.$set(this.file, "type", newVal.fullName.split(".")[1]);
        }
      },
      // 立即执行handler方法
      immediate: true,
      // 深度监听，常用于对象下面属性的改变
      deep: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.PictureUpload {
  > label {
    display: block;
    width: 80px;
    height: 32px;
    border: 1px solid #666666;
    cursor: pointer;
    text-align: center;
    line-height: 32px;
  }
  > input {
    display: none;
  }
}
</style>